var gulp = require('gulp');
var stylus = require('gulp-stylus');
var postcss = require('gulp-postcss');
var sourcemaps = require('gulp-sourcemaps');
var cssimport = require("gulp-cssimport");
var livere = require('gulp-livereload');
var uglifyJs = require('gulp-uglify');
var rename = require("gulp-rename");
var babel = require('gulp-babel');
var replace = require('gulp-just-replace');
var production = process.env.PRODUCTION;
var publicPath = '/letsCoffee'

gulp.task('stylus', function () {
    gulp.src(['./src/pages/**/css/*.styl'])
        .pipe(replace(/ctx/g, production ? publicPath : ''))
        .pipe(stylus({
            compress: true
        }))
        .pipe(cssimport())
        .pipe(sourcemaps.init())
        .pipe(postcss(require('postcss-import'), require('postcss-cssnext'), require('autoprefixer')))
        .pipe(rename(function (path) {
            path.extname = '.min' + path.extname;
        }))
        .pipe(gulp.dest('./build/'))
});
gulp.task('html', function () {
    gulp.src(['./src/pages/**/*.html'])
    .pipe(replace(/ctx/g, production ? publicPath : ''))
    .pipe(replace(/static_build_time/g, new Date().getTime()))
    // .pipe(function (html) {
    //     console.log(html);h
    //     return html;
    // })
    .pipe(gulp.dest('./build/'));
});

gulp.task('js', function () {
    gulp.src(['./src/pages/**/js/*.js'])
    // .pipe(uglifyJs())
    .pipe(rename(function (path) {
        path.extname = '.min' + path.extname;
    }))
    .pipe(gulp.dest('./build/'))
});
gulp.task('jslib', function () {
    gulp.src(['./src/pages/**/js/lib/*.js'])
    .pipe(babel())
    // .pipe(uglifyJs())
    .pipe(rename(function (path) {
        path.extname = '.min' + path.extname;
    }))
    .pipe(gulp.dest('./build/'))
})
gulp.task('images', function () {
    gulp.src(['./src/pages/**/images/**/*.png', './src/**/images/**/*.png'])
    .pipe(gulp.dest('./build/'))
});
gulp.task('build', ['html', 'stylus', 'js', 'jslib', 'images']);
gulp.task('watch', function(){
    gulp.watch(['./src/pages/**'], ['build'])
    .on('change', function(){
        livere.listen();
    });
});
